import { GetApi, PostApi, Promisify, goError } from './utils/util'
import { storage } from './utils/wxapi'

App({
	globalData: {},
	onShow(options) {
		if (options.scene === 1044) {
			this.globalData.shareTicket = options.shareTicket
			console.log('shareTicket', this.globalData.shareTicket)
		}
	},
	// 获取配置
	getConfig() {
		if (this.globalData.config) {
			return Promise.resolve(this.globalData.config)
		}
		return GetApi(`/config`).then(
			data => {
				this.globalData.config = data
				return data
			},
			err => {
				console.log('===============')
				console.log(err)
				console.log('===============')
				if (
					err.errMsg === 'request:fail timeout' ||
					err.errMsg === 'request:fail 请求超时。'
				) {
					goError(103, '请求超时', '请检查网络后重试')
				} else {
					goError(102, '加载身份标识失败', err.msg || err.errMsg)
				}
				return
			}
		)
	},
	// 获取token
	fetchToken(res) {
		return Promisify(wx.login)().then(res => {
			if (res.code) {
				return PostApi(this.globalData.config.fetch_token_url, {
					code: res.code
				}).then(data => {
					return data.token
				})
			} else {
				return goError(102, '获取登录状态失败', res.errMsg)
			}
		})
	},
	// 获取用户信息
	getUserInfo(forceFetch = false) {
		if (!forceFetch && this.globalData.userInfo) {
			return Promise.resolve(this.globalData.userInfo)
		}
		return GetApi(`/user`, { force: forceFetch })
			.then(res => {
				const user = res.user
				// 用户手机号换成*
				if (user.mobile.length == 11) {
					user.mobile =
						user.mobile.slice(0, 3) + '****' + user.mobile.slice(7)
				}
				this.globalData.userInfo = res.user
				return res.user
			})
			.catch(err => {
				if (
					err.errMsg === 'request:fail timeout' ||
					err.errMsg === 'request:fail 请求超时。'
				) {
					goError(103, '请求超时', '请检查网络后重试')
					return {}
				} else if (err.auth == -1) {
					return this.fetchToken()
						.then(token => {
							return storage
								.set('token', token)
								.then(() => {
									return this.getUserInfo()
								})
								.catch(err => {
									console.log('设置 storage 失败: ', err)
									console.log('key = token')
								})
						})
						.catch(err => {
							console.log(err)
							if (
								err.errMsg === 'request:fail timeout' ||
								err.errMsg === 'request:fail 请求超时。'
							) {
								goError(
									103,
									'获取token超时',
									'请检查网络后重试'
								)
							} else {
								goError(102, '加载身份标识失败', err.errmsg)
							}
							return {}
						})
				} else {
					goError(102, '加载身份标识失败', err.msg || err.errMsg)
					return {}
				}
			})
	}
})
